// -*-mode:c++; coding:utf-8-*-

#include <iostream>
#include <sstream>
#include <string>

using namespace std;

#include <boost/asio.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/thread/mutex.hpp>

#include <xbase_utility.hpp>
#include <naming_strategy.hpp>

#include "protocol.hpp"
#include "io_service_pool_impl.hpp"
#include "session_manager.hpp"
#include "meta_tablet_scanner.hpp"

using namespace xbase;

typedef boost::system::error_code error_code;

void on_get_next_row(meta_tablet_scanner *mts, meta_row_result::ptr_type row_ptr, const error_code &ec)
{
	if(ec)
	{
		std::cout << "get next row failed : " << ec
			<< " - " << ec.message() << std::endl;
	}
	else
	{
		std::cout << "tabletInfo: " << row_ptr->m_tablet_info.to_string() << endl;
		std::cout << "serverAddress: " << row_ptr->m_server_address.to_string() << endl;
		std::cout << "serverStartCode: " << row_ptr->m_server_start_code << endl;
		std::cout << "splitA: " << row_ptr->m_splitA << endl;
		std::cout << "splitB: " << row_ptr->m_splitB << endl;
		std::cout << endl;

		std::cout << "pause...";
		std::cin.get();
		mts->async_get_next_row(boost::bind(on_get_next_row, mts, _1, _2));
	}
}

int main(int argc, char **argv)
{
	if(argc!=5)
	{
		cout <<argv[0]<<" tablet_ip tablet_port start_row end_row"<< endl;
		return 0;
	}

	boost::asio::ip::tcp::endpoint endpoint(
		boost::asio::ip::address::from_string(argv[1]),
		::atoi(argv[2])
		);

	std::string start_row = argv[3];
	std::string end_row = argv[4];

	boost::shared_ptr<io_service_pool> pool(new impl::single_io_service());
	client_options options;
	pool->set_options(options);
	pool->run();

	session_manager sm(*pool);

	meta_tablet_scanner_ptr mts_ptr(new meta_tablet_scanner(*pool, endpoint, sm, start_row, end_row));
	meta_tablet_scanner &mts = *mts_ptr;

	mts.async_get_next_row(boost::bind(on_get_next_row, &mts, _1, _2));

	std::string input;
	while(std::cin >> input)
	{
		if(input == "close")
		{
			sm.close();
		}
		else if(input == "quit")
		{
			break;
		}
	}

	pool->stop();
	pool->join();

	return 0;
}
